package org.jeecg.modules.knowledge.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.MQConstant;
import org.jeecg.common.mq.config.ActiveMQBeanConfig;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.constant.ConsumerConstant;
import org.jeecg.constant.ElasticSearchConstant;
import org.jeecg.constant.RedisConstant;
import org.jeecg.modules.article.vo.ToGetTopicArticleDetailVO;
import org.jeecg.modules.es.service.ElasticSearchService;
import org.jeecg.modules.es.vo.KnowledgeVO;
import org.jeecg.modules.knowledge.entity.PhilKnowledge;
import org.jeecg.modules.knowledge.service.IPhilKnowledgeService;
import org.jeecg.modules.knowledgerelation.KnowledgeTreeVO;
import org.jeecg.modules.knowledgerelation.entity.KnowledgeRelation;
import org.jeecg.modules.knowledgerelation.service.IKnowledgeRelationService;
import org.jeecg.modules.wechat.service.IWxUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @Description: 知识
 * @Author: jeecg-boot
 * @Date:   2020-12-20
 * @Version: V1.0
 */
@Api(tags="知识")
@RestController
@RequestMapping("/knowledge")
@Slf4j
public class PhilKnowledgeController extends JeecgController<PhilKnowledge, IPhilKnowledgeService> {
	@Autowired
	private IPhilKnowledgeService philKnowledgeService;
	@Autowired
	private ElasticSearchService elasticSearchService;
	@Autowired
	private ActiveMQBeanConfig activeMQBeanConfig;
	@Autowired
	private JmsMessagingTemplate jmsMessagingTemplate;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private IKnowledgeRelationService knowledgeRelationService;
	@Autowired
	private IWxUserService wxUserService;
	/**
	 * 分页列表查询
	 *
	 * @param philKnowledge
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "知识-分页列表查询")
	@ApiOperation(value="知识-分页列表查询", notes="知识-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(PhilKnowledge philKnowledge,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<PhilKnowledge> queryWrapper = QueryGenerator.initQueryWrapper(philKnowledge, req.getParameterMap());
		Page<PhilKnowledge> page = new Page<PhilKnowledge>(pageNo, pageSize);
		IPage<PhilKnowledge> pageList = philKnowledgeService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param philKnowledge
	 * @return
	 */
	@AutoLog(value = "知识-添加")
	@ApiOperation(value="知识-添加", notes="知识-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody PhilKnowledge philKnowledge) throws IOException {
		// 获取雪花id，并设置文章id
		Snowflake snowflake = IdUtil.createSnowflake(1,1);
		String id = snowflake.nextIdStr();
		philKnowledge.setId(id);
		philKnowledgeService.save(philKnowledge);
		philKnowledgeService.insertKeywordKnowledge(philKnowledge);
		// 更新es
		Map<String, Object> map = new HashMap<>();
		map.put(MQConstant.OPERATION, ConsumerConstant.PHIL_PUBLISH_KNOWLEDGE);
		map.put(MQConstant.INFO, JSON.toJSONString(philKnowledge));
		jmsMessagingTemplate.convertAndSend(activeMQBeanConfig.queueTopicRedis(),map);

		return Result.ok("添加成功");
	}
	
	/**
	 *  编辑
	 *
	 * @param philKnowledge
	 * @return
	 */
	@AutoLog(value = "知识-编辑")
	@ApiOperation(value="知识-编辑", notes="知识-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody PhilKnowledge philKnowledge) {
		String id = philKnowledge.getId();
		philKnowledge.setKnowledgeImageString(philKnowledge.getKnowledgeImageString());
		KnowledgeVO knowledgeVO = new KnowledgeVO();
		BeanUtils.copyProperties(philKnowledge,knowledgeVO);
		String[] split = philKnowledge.getKnowledgeKeywords().split(",");
		List<String> strings = Arrays.asList(split);
		knowledgeVO.setKeywordList(strings);
		elasticSearchService.updateDocument(ElasticSearchConstant.PHIL_KNOWLEDGE,id,knowledgeVO,"10s");
		philKnowledgeService.updateById(philKnowledge);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "知识-通过id删除")
	@ApiOperation(value="知识-通过id删除", notes="知识-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		PhilKnowledge knowledge = philKnowledgeService.getById(id);
		// 删除全文检索中的信息
		elasticSearchService.deleteDocument(ElasticSearchConstant.PHIL_KNOWLEDGE,id,"10s");
		// 删除知识
		philKnowledgeService.removeById(id);
		// 删除关系
		knowledgeRelationService.remove(
				new LambdaQueryWrapper<KnowledgeRelation>()
				.eq(KnowledgeRelation::getKnowledgeFromId,knowledge.getId()));
		// 删除关键字
		philKnowledgeService.delKeywordKnowledge(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "知识-批量删除")
	@ApiOperation(value="知识-批量删除", notes="知识-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		List<String> list = Arrays.asList(ids.split(","));
		// 获取知识信息
		List<PhilKnowledge> infos = philKnowledgeService.listByIds(list);
		this.philKnowledgeService.removeByIds(Arrays.asList(ids.split(",")));
		infos.forEach(res->{
			elasticSearchService.deleteDocument(ElasticSearchConstant.PHIL_KNOWLEDGE,res.getId(),"10s");
			// 删除关系
			knowledgeRelationService.remove(
					new LambdaQueryWrapper<KnowledgeRelation>()
							.eq(KnowledgeRelation::getKnowledgeFromId,res.getId()));
			// 删除关键字
			philKnowledgeService.delKeywordKnowledge(res.getId());
		});
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "知识-通过id查询")
	@ApiOperation(value="知识-通过id查询", notes="知识-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id,@RequestParam(name = "openId",required = false) String openId) {
		PhilKnowledge philKnowledge = philKnowledgeService.getById(id);
		if(philKnowledge==null) {
			return Result.error("未找到对应数据");
		}
		//判断用户是否加分
		if (StrUtil.isNotBlank(openId)) {
			long res = redisUtil.sSet(RedisConstant.READING + id, openId);
			if (res==1){
				// 说明是今天第一次阅读本文章，加分
				wxUserService.updateUserScore(openId,true,1);
			}
		}
		// 返回知识详情和树结构
		List<KnowledgeTreeVO> treeVOList = knowledgeRelationService.getTreeByknowledge(id);
		philKnowledgeService.incrReadNum(id);
		HashMap<String, Object> map = new HashMap<>(2);
		map.put("info",philKnowledge);
		map.put("tree",treeVOList);
		return Result.OK(map);
	}
	/**
	 * 通过类别获取集合
	 *
	 * @param knowledgeType 知识类别（栏目）
	 * @return
	 */
	@AutoLog(value = "知识-通过类别获取集合")
	@ApiOperation(value="知识-通过类别获取集合", notes="知识-通过类别获取集合")
	@GetMapping(value = "/queryByType")
	public Result<?> queryByType(@RequestParam(name="knowledgeType",required=true) String knowledgeType,
								 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {

		Page<PhilKnowledge> page = new Page<PhilKnowledge>(pageNo, pageSize);
		Page<PhilKnowledge> pageList = philKnowledgeService.getSortKnowledgeByType(page,knowledgeType);
		return Result.OK(pageList);
	}
	/**
	 * 通过ids获取知识详情
	 *
	 * @return
	 */
	@AutoLog(value = "知识-获取新推知识")
	@ApiOperation(value="知识-获取新推知识", notes="知识-获取新推知识")
	@PostMapping(value = "/queryNewKnowledge")
	public Result<?> queryNewKnowledge(@RequestBody ToGetTopicArticleDetailVO getTopicArticleDetailVO) {
		String openId = getTopicArticleDetailVO.getOpenId();
		String columnId = getTopicArticleDetailVO.getColumnId();

		// 从redis中获取栏目id并置为空
		HashMap<String, Object> map= (HashMap<String, Object>) redisUtil.get(RedisConstant.ARTICLE_PUBLISH + columnId);
		Object o = map.get(openId);
		if (o==null){
			return Result.OK();
		}
		Set<String> set = (Set<String>)o;
		List<PhilKnowledge> list = philKnowledgeService.listByIds(set);
		// 异步清空该栏目下该用户的推送文章
		Map<String, String> info = new HashMap<>(2);
		info.put("openId",openId);
		info.put("columnId",columnId);
		Map<String, Object> map2 = new HashMap<>(2);
		map2.put(MQConstant.OPERATION,ConsumerConstant.PHIL_CLEAR_COLUMN_PUBLISH_ARTICLE);
		map2.put(MQConstant.INFO, JSON.toJSONString(info));
		jmsMessagingTemplate.convertAndSend(activeMQBeanConfig.queueTopicRedis(),map2);

		return Result.OK(list);
	}
    /**
    * 导出excel
    *
    * @param request
    * @param philKnowledge
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, PhilKnowledge philKnowledge) {
        return super.exportXls(request, philKnowledge, PhilKnowledge.class, "知识");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, PhilKnowledge.class);
    }


	/**
	 * 通过关键字获取集合
	 *
	 * @param keyword 知识类别（栏目）
	 * @return
	 */
	@AutoLog(value = "知识-通过关键字获取集合")
	@ApiOperation(value="知识-通过关键字获取集合", notes="知识-通过关键字获取集合")
	@GetMapping(value = "/queryByKeyword")
	public Result<?> queryByKeyword(@RequestParam(name="keyword",required=true) String keyword,
								 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
		Page<PhilKnowledge> page = new Page<PhilKnowledge>(pageNo, pageSize);
		Page<PhilKnowledge> pageList = philKnowledgeService.getSortKnowledgeByKeyword(page,keyword);
		return Result.OK(pageList);
	}

}
